package com.banggood.upms.service.impl;

import com.banggood.silk.web.api.exception.SkbException;
import com.banggood.upms.bean.exception.ExceptionEnum;
import com.banggood.upms.bean.po.UserScope;
import com.banggood.upms.common.constant.UpmsConstant;
import com.banggood.upms.dao.UserScopeDao;
import com.banggood.upms.service.UserScopeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @author XuChuangFeng
 */
@Service
@Transactional(rollbackFor = SkbException.class)
public class UserScopeServiceImpl extends BaseServiceImpl<UserScope, UserScopeDao> implements UserScopeService {

    @Override
    @Autowired
    public void setDao(UserScopeDao dao) {
        super.dao = dao;
    }

    @Override
    public int insert(UserScope record) throws Exception {
        if(this.ifScopeKeyExist(record.getScopeKey())) {
            throw new SkbException(ExceptionEnum.USER_SCOPE_ALREADY_EXIST.getCode(), ExceptionEnum.USER_SCOPE_ALREADY_EXIST.getMessage());
        }
        return dao.insert(record);
    }

    @Override
    public boolean ifScopeKeyValidate(String scopeKey) {
        if(StringUtils.isEmpty(scopeKey) || !scopeKey.startsWith(UpmsConstant.SLASH)) {
            return false;
        }
        return true;
    }

    /**
     * 只检测一级用户域
     * @param scopeKey
     * @return
     */
    @Override
    public boolean ifScopeKeyExist(String scopeKey) throws SkbException {
        String firstScopeKey;
        if(!this.ifScopeKeyValidate(scopeKey)) {
            throw new SkbException(ExceptionEnum.INVALIDATE_USER_SCOPE.getCode(), ExceptionEnum.INVALIDATE_USER_SCOPE.getMessage());
        }
        int secondSlashIndex = scopeKey.indexOf("/", 1);
        if(secondSlashIndex < 0) {
            firstScopeKey = scopeKey;
        } else {
            firstScopeKey = scopeKey.substring(0, secondSlashIndex);
        }
        return dao.getScopeByKey(firstScopeKey) != null ? true : false;
    }
}
